package net.zypro.sample.controller;

import javax.servlet.http.HttpServletRequest;

import net.zypro.sample.exception.LoginFailedException;
import net.zypro.sample.model.Account;
import net.zypro.sample.model.ErrorMessage;
import net.zypro.sample.service.AccountService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AccountController {
	
	@Autowired
	private AccountService accountService;
	
	/*
	@RequestMapping(value="/login")
	@ResponseBody
	public Account login(@RequestBody Account a) throws LoginFailedException
	{
		Account account=accountService.login(a.getUsername(),a.getPassword());
		
		if(account!=null)
		{
			return account;
		}else{
			throw new LoginFailedException("用户名或密码错误");
		}
	} */
	@RequestMapping(value="/login")
	public Account login(@RequestParam(value="username",required=true)String username,@RequestParam(value="password",required=true)String password) throws LoginFailedException
	{
		Account account=accountService.login(username,password);
		
		if(account!=null)
		{
			return account;
		}else{
			throw new LoginFailedException("用户名或密码错误");
		}
	}
	
	
	@RequestMapping(value="/error")
	public ErrorMessage handleError(HttpServletRequest request)
	{
		int status=Integer.parseInt(request.getAttribute("javax.servlet.error.status_code").toString());
		//String msg=request.getAttribute("javax.servlet.error.message").toString();
		
		Throwable throwable = (Throwable)request.getAttribute("javax.servlet.error.exception");
		
		ErrorMessage error=new ErrorMessage();
		
		switch (status) {
			case 400:
				error=new ErrorMessage(ErrorMessage.CLIENT_PARAMS_ERROR);
				break;
			case 404:
				error=new ErrorMessage(ErrorMessage.SERVICE_UNAVAILABLE_ERROR); 
				break;
			case 500:
				if(throwable.getCause() instanceof LoginFailedException)
				{
					error.setCode(ErrorMessage.USER_AUTH_FAILED_ERROR);
					error.setMessage(throwable.getCause().getMessage());
				}else{
					error=new ErrorMessage(ErrorMessage.SERVER_UNKNOWN_ERROR);
				}
				
				break;
			default:

				error=new ErrorMessage(ErrorMessage.SERVER_UNKNOWN_ERROR);
				
				break;
		}
		
		return error;
	}
}
